#-*- coding: utf-8 -*-
#! /usr/bin/python

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
import sys
import win32api
import win32con
#from selenium.common.exceptions import NoSuchElementException
#from selenium.webdriver.common.keys import Keys
import time
import httplib
import re
import base64

reload(sys)
sys.setdefaultencoding("utf-8")

def lgRouter():
    # 192.168.1.1
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
        "Connection": "keep-alive"}

    # get status page
    conn.request("GET", "/userRpm/StatusRpm.htm", "", headers)
    response = conn.getresponse()
    keyword = re.search(' wanPara [^\)]*?\)', response.read())
    response.close()
    conn.close()

    # search the public ip address
    found = 0
    publicIP = ""
    if keyword:
        arr = re.findall('([\d]*?,)|(\"[^\"]*?\",)', keyword.group(0))
        if arr:
            if len(arr) > 3:
                publicIP = re.search('(?<=\")[^\"]*?(?=\")', arr[2][1])
                if publicIP:
                    publicIP = publicIP.group(0)
                    found = 1

    if found == 1:
        return publicIP
    else:
        return "Error"

def diconectRouter():
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
        "Connection": "keep-alive"}  

    sparam = "?Disconnect=%B6%CF%20%CF%DF&wan=1"    
    conn.request("GET", "/userRpm/StatusRpm.htm"+sparam, "", headers)    
    response = conn.getresponse()
    keyword = re.search(' wanPara [^\)]*?\)', response.read())
    response.close()
    conn.close()
    
    # search the public ip address
    found = 0
    publicIP = ""
    if keyword:
        arr = re.findall('([\d]*?,)|(\"[^\"]*?\",)', keyword.group(0))
        if arr:
            if len(arr) > 3:
                publicIP = re.search('(?<=\")[^\"]*?(?=\")', arr[2][1])
                if publicIP:
                    publicIP = publicIP.group(0)
                    found = 1
    if(publicIP == '0.0.0.0'):
        #print "disconect!"
        return True
    else:
        #print publicIP
        return False


def connectRouter():
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.9,*;q=0.8",
        "Referer": "http://192.168.1.1/userRpm/StatusRpm.htm",
        "Host": "192.168.1.1",
        "Connection": "keep-alive"}  

    sparam = "?Connect=%C1%AC%20%BD%D3&wan=1"    
    conn.request("GET", "/userRpm/StatusRpm.htm"+sparam, "", headers)
    conn.close()
    time.sleep(4)
    rt = lgRouter()

    if(rt=="0.0.0.0"):
        print "Status is disconect"        
    else:
        if(rt=="Error"):
            print "Status is Error"
        else:
            print "Status is conect,ip is "+rt
    return rt

def changeip():
    rt = lgRouter()
    if(rt=="0.0.0.0"):
        print "Status is disconect"
    else:
        if(rt=="Error"):
            print "Status is Error"
        else:
            print "Status is conect,ip is "+rt
    rt = diconectRouter()
    if(rt):
        print "Disconect the Router Successfully"
    time.sleep(3)
    rtt = connectRouter()
    i =  5
    while((rtt == rt) and (i>0)):
        diconectRouter()
        rtt = connectRouter()
        i = i - 1

def keybd(keynum):
    win32api.keybd_event(keynum, 0, 0, 0)
    time.sleep(0.5)
    win32api.keybd_event(keynum, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(0.5)


def inputPass(passwd):
    '''
    模拟键盘输入密码
    passwd是一个list,大小写都可处理
    '''
    time.sleep(0.2)
    psht = len(passwd)
    ppass = list(passwd)
    for j in range(psht):
        print ord(ppass[j])
        if(ppass[j].isupper()):
            win32api.keybd_event(20, 0, 0, 0)#按下CAPS按键
            time.sleep(0.1)
            win32api.keybd_event(20, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.1)
            win32api.keybd_event(ord(ppass[j]), 0, 0, 0)#按下按键
            time.sleep(0.1)
            win32api.keybd_event(ord(ppass[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.2)
            win32api.keybd_event(20, 0, 0, 0)#按下CAPS按键
            time.sleep(0.1)
            win32api.keybd_event(20, 0, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(0.1)
        else:
            if(ppass[j].isalpha()):
                knum = ord(ppass[j])-32
            else:
                knum = ord(ppass[j])
            win32api.keybd_event(knum, 0, 0, 0)#按下按键
            time.sleep(0.1)
            win32api.keybd_event(knum, 0, win32con.KEYEVENTF_KEYUP, 0)        
            time.sleep(0.1)


def loginAlipay(username,password):
    '''
    aliname一般是一个email
    login alipay
    '''
    chrome.delete_all_cookies()
    lgurl = 'https://auth.alipay.com/login/index.htm?goto=https%3A%2F%2Flab.alipay.com%2Fuser%2Fi.htm'
    chrome.get(lgurl)
    try:
        chrome.find_element_by_class_name('nickx').click()
    except:
        pass 
    try:
        txtname = chrome.find_element_by_id("logonId")
        chrome.execute_script("document.getElementById('logonId').value = ''")
        txtname.send_keys(username)
        txtname.click()
    except:
        print 'fail to send username'
    keybd(9)#tab
    inputPass(password)
    try:
        sbtn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("submit_btn"))
        sbtn.submit()
    except:
        print 'fail to get element submit_btn'
    #lgok = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id('global-username'))
    #lgok = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id('JAsideMultiAccTrigger'))
        
    

def logoutAlipay():
    '''
    logout from taobao
    '''
    lurl = "http://login.taobao.com/member/logout.jhtml?spm=a1z02.1.0.6.wXTWrc&amp;f=top&amp;out=true&amp;redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fnekot%3Ds6S6%252BtfTtcTQodHy1351908154890"
    chrome.get(lurl)


def logit(content, filename='log.txt'):
    '''
    逐行添加日志，每行一个回车
    头部是时间
    '''
    file = open(filename, 'a')
    try:
        file.write(content+'\r\n')
    finally:
        file.close()



def zhifubpay(ppass):
    '''
    支付宝有钱用支付宝支付
    '''
    time.sleep(1.5)
    try:#输入密码
        pbox = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_class_name("alieditContainer"))
        pbox.click()
        inputPass(ppass)
    except:
        print 'fail to get element alieditContainer'
    try:#确认支付
        btn2 = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_authSubmit"))
        btn2.submit()
    except:
        print 'fail to get element J_authSubmit'

def cashpay(ppass):
    '''
    支付宝没钱，用卡付款，估计需要短信
    '''

def pay(url, ppass):
    '''
    alipay url link
    '''
    time.sleep(0.7)
    chrome.stop_client()
    chrome.get(url)
    time.sleep(1.4)
    chrome.stop_client()  
    try:#checkbox选中
        ckp = chrome.find_element_by_id('agreePay')
        ckp.click()
        chrome.execute_script("document.getElementById('agreePay').checked = true ")
    except:
        print 'fail to get element agreePay'
    try:#submit to pya 确认付款
        btn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("confirmFormSubmit"))
        btn.submit()
    except:
        print 'fail to get element confirmFormSubmit'
    #cashpay(ppass)
    zhifubpay(ppass)
    




'''
循环处理代付款链接，挨个付款
'''
chrome = webdriver.Ie()
#chrome = webdriver.Chrome()
chrome.delete_all_cookies()

username = '13735643100'
password = 'JHF178TQ3JX8'
ppass = 'TQ3JX977'
username = 'yanyu2008@sogou.com'
password = 'JHFtDongtq3'
ppass = 'TQ3JX8'

#url = 'https://shenghuo.alipay.com/peerpaycore/confirmPeerPay.htm?id=20121107142654662&sign=6d54a1cb'
url ='https://shenghuo.alipay.com/peerpaycore/confirmPeerPay.htm?id=20121108142799282&sign=c055e7d2'
try:
    changeip()
except:
    print 'fail to change ip'

loginAlipay(username,password)
time.sleep(1.3)
pay(url, ppass)
chrome.delete_all_cookies()



